def InsertSort(data):          #插入排序
    for i in range(len(data)):
        temp = data[i]
        j = i - 1
        while j >= 0 and temp < data[j]:
            data[j+1] = data[j]
            j -= 1
        data[j+1] = temp

def bubbleSort(arr):            #冒泡排序
    n = len(arr)
    # 遍历所有数组元素
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1] :
                arr[j], arr[j+1] = arr[j+1], arr[j]

    def partition(arr,low,high): 
        i = ( low-1 )         # 最小元素索引
        pivot = arr[high]     
  
        for j in range(low , high): 
            if   arr[j] <= pivot: 
          
                i = i+1 
                arr[i],arr[j] = arr[j],arr[i] 
  
        arr[i+1],arr[high] = arr[high],arr[i+1] 
        return ( i+1 ) 
  
def partition(arr, low, high):
    i = (low - 1)  # 最小元素索引
    pivot = arr[high]

    for j in range(low, high):
        if arr[j] <= pivot:
            i = i + 1
            arr[i], arr[j] = arr[j], arr[i]

    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return (i + 1)

def quick_sort(list, low = None, high = None):  #快速排序
    low=0 if not isinstance(low,int) else low
    high=len (list)-1 if not isinstance(high,int) else high 
    if low <high :
        PartitionIndex = partition (list ,low ,high )
        quick_sort(list ,low ,PartitionIndex - 1)
        quick_sort(list ,PartitionIndex + 1,high)
        return list


def heapSort(List):
    size = len(List)
    buildMaxHeap(List, size)
    i = size - 1
    while i > 0:
        swap(List, i, 0)
        size = size - 1
        heapify(List, 0, size)
        i = i - 1
    return List


def heapify(List, i, size):
    left = i * 2 + 1
    right = i * 2 + 2
    largest = i
    if left < size and List[largest] < List[left]:
        largest = left
    if right < size and List[largest] < List[right]:
        largest = right
    if largest != i:
        swap(List, largest, i)
        heapify(List, largest, size)


def buildMaxHeap(List, size):
    i = int(size / 2)
    while i >= 0:
        heapify(List, i, size)
        i = i - 1


def swap(List, i, j):
    temp = List[i]
    List[i] = List[j]
    List[j] = temp


def merge_sort(alist):
    if len(alist) <= 1:
        return alist
    # 二分分解
    num = len(alist)//2
    left = merge_sort(alist[:num])
    right = merge_sort(alist[num:])
    # 合并
    return merge(left,right)

def merge(left, right):
    '''合并操作，将两个有序数组left[]和right[]合并成一个大的有序数组'''
    #left与right的下标指针
    l, r = 0, 0
    result = []
    while l<len(left) and r<len(right):
        if left[l] <= right[r]:
            result.append(left[l])
            l += 1
        else:
            result.append(right[r])
            r += 1
    result += left[l:]
    result += right[r:]
    return result